package ru.amse.stroganova.ui.tool;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;

import ru.amse.stroganova.presentation.VertexPresentation;
import ru.amse.stroganova.ui.GraphComponent;
import ru.amse.stroganova.ui.command.Command;

/*package*/ class AddEdgeTool extends Tool {

	private final GraphComponent component;

	private Point end;
	
	private VertexPresentation source;
	
	private VertexPresentation destination;

	/*package*/ AddEdgeTool(GraphComponent component) {
		this.component = component;
	}

	@Override
	public void mousePressed(MouseEvent e) {
		component.getGraphElementSelection().unselect();
		source = component.getGraphElementSelection().getVertex(e.getPoint());
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		destination = component.getGraphElementSelection().getVertex(e.getPoint());
		if ((source != null) && (destination != null) && !component.getGraphPresentation().areConnected(source, destination)) {
			//TODO Eliminate it when selfLoops can be drawn
			if (!source.equals(destination)) {
				Command command = component.getCommandFactory()
											.getNewAddEdgeCommand(source, destination);
				component.addCommand(command);
				command.execute();
			}
		}
		end = null;
		component.repaint();
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		end = e.getPoint();
		component.repaint();
	}

	@Override
	public void finalActions() {
		component.repaint();
	}

	@Override
	public void paint(Graphics gr, Color color) {
		gr.setColor(Color.RED);
		if ((source != null) && (end != null)) {
			gr.drawLine(source.getCenter().x, source.getCenter().y, end.x, end.y);
		}
	}
}
